<?php

namespace App\Models\Traits;

use App\Models\Comment;
use App\Models\Product;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

trait CommentCacheTrait
{
	public static function sProductCommentsCacheKey($pid)
	{
		return "product_{$pid}_comments";
	}
	
	public static function sProductCommentsCountCacheKey($pid)
	{
		return "product_{$pid}_comments_count";
	}
	
	public static function sCacheKey($comId)
	{
		return "product_comment_{$comId}";
	}
	
	public static function sGetProductComments($pid, $index)
	{
		$comments = collect();
		
		$limit = $index + 9;
		$index = $index > 0 ? $index+1 : $index;
		$cachedIds = Redis::zRange(self::sProductCommentsCacheKey($pid), $index, $limit);
		
		if (count($cachedIds) <= 0) return collect();
		
		foreach ($cachedIds as $comId) {
			$comment = self::sGetCache($comId);
			$comments->push($comment);
			Log::debug("Get comment: {$comId}");
		}
		
		return $comments;
	}
	
	public static function sProductCommentsCount($pid)
	{
		return Redis::zCard(self::sProductCommentsCacheKey($pid));
	}
	
	public static function sGetCache($id)
	{
		if (! Cache::has(self::sCacheKey($id))) {
			$comment = Comment::find($id);
			$comment->addToCache();
			Log::debug("Comment: {$comment->id} first cached");
		}
		return Cache::get(self::sCacheKey($id));
	}
	
	/*==================================================================================================================*/
	
	
	public function CacheKey()
	{
		return self::sCacheKey($this->id);
	}
	
	public function cacheFields()
	{
		return [
			'id' => (int)$this->id,
			'user_id' => (int)$this->user_id,
			'user_avatar_url' => img_path($this->user->avatar),
			'user_name' => $this->user->name,
			'content' => (string)$this->content,
			'images' => $this->images,
			'created_at' => (string)$this->created_at,
			'is_favor' => (bool)$this->is_favor,
		];
	}
	
	public function addToCache()
	{
		$data = $this->cacheFields();
		Cache::put($this->cacheKey(), $data, cache_time());
		
		if ($this->commentable instanceof Product) {
			$product = $this->commentable;
			Redis::zAdd(self::sProductCommentsCacheKey($product->id), $this->id, $this->id);
			Log::debug("Comment: {$this->id} added to cache");
		}
	}
	
	public function delFromCache()
	{
		Cache::forget($this->cacheKey());
		Redis::zRem(self::sProductCommentsCacheKey($this->id), $this->id);
	}
}
